package com.cjz.roomdbdemo.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cjz.roomdbdemo.R;
import com.cjz.roomdbdemo.db.Note;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 笔记列表adapter
 * <p>
 * Created by cjz on 2018/8/31.
 */
public class NoteListAdapter extends RecyclerView.Adapter<NoteListAdapter.NoteViewHolder> {


    private List<Note> mNotes;


    private final LayoutInflater mInflater;

    public NoteListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    }

    @NonNull
    @Override
    public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new NoteViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull NoteViewHolder holder, int position) {
        if (mNotes != null && mNotes.size() > 0) {
            Note current = mNotes.get(position);

            java.util.Date date = new Date(current.getInsertTime());
            String str = sdf.format(date);


            holder.textView.setText(new StringBuilder().append(str).append("\n").append(current.getNote()).toString());
        }
    }


    SimpleDateFormat sdf;


    @Override
    public int getItemCount() {
        if (mNotes != null) {
            return mNotes.size();
        } else {
            return 0;
        }
    }

    public void setNotes(List<Note> notes) {
        this.mNotes = notes;
        notifyDataSetChanged();
    }

    public static class NoteViewHolder extends RecyclerView.ViewHolder {

        TextView textView;

        public NoteViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
        }
    }
}
